package com.lw.leetcode.hash.c;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * map
 * 2488. 统计中位数为 K 的子数组
 *
 * @author liw
 * @version 1.0
 * @date 2022/11/28 20:44
 */
public class CountSubarrays {

    public int countSubarrays(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        boolean f = false;
        map.put(0, 1);
        int sum = 0;
        int count = 0;
        for (int num : nums) {
            if (num == k) {
                f = true;
            } else if (num < k) {
                sum--;
            } else {
                sum++;
            }
            if (f) {
                count += map.getOrDefault(sum, 0);
                count += map.getOrDefault(sum - 1, 0);
            } else {
                map.merge(sum, 1, (a, b) -> a + b);
            }
        }
        return count;
    }

}
